"""
@Author  : 康帅
@Time    : 2021/6/11 17:56
@Function: 腾讯云对象存储
"""


# -*- coding=utf-8
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
from qcloud_cos import CosServiceError
from qcloud_cos import CosClientError
import sys
import logging

logging.basicConfig(level=logging.INFO, stream=sys.stdout)

# 设置用户属性, 包括 secret_id, secret_key, region
# APPID 已在配置中移除，请在参数 Bucket 中带上 APPID。Bucket 由 BucketName-APPID 组成
secret_id = 'secret_id'  # 替换为用户的 secret_id
secret_key = 'secret_key'  # 替换为用户的 secret_key
region = 'ap-beijing'  # 替换为用户的 region
token = None  # 使用临时密钥需要传入 Token，默认为空,可不填
config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token)  # 获取配置对象
client = CosS3Client(config)

# 文件流 简单上传
file_name = 'test.txt'
with open('test.txt', 'rb') as fp:
    response = client.put_object(
        Bucket='examplebucket-1250000000',  # Bucket 由 BucketName-APPID 组成
        Body=fp,
        Key=file_name,
        StorageClass='STANDARD',
        ContentType='text/html; charset=utf-8'
    )
    print(response['ETag'])
# 字节流 简单上传
response = client.put_object(
    Bucket='examplebucket-1250000000',
    Body=b'abcdefg',
    Key=file_name
)
print(response['ETag'])
# 本地路径 简单上传
response = client.put_object_from_local_file(
    Bucket='examplebucket-1250000000',
    LocalFilePath='local.txt',
    Key=file_name,
)
print(response['ETag'])
# 设置 HTTP 头部 简单上传
response = client.put_object(
    Bucket='examplebucket-1250000000',
    Body=b'test',
    Key=file_name,
    ContentType='text/html; charset=utf-8'
)
print(response['ETag'])
# 设置自定义头部 简单上传
response = client.put_object(
    Bucket='examplebucket-1250000000',
    Body=b'test',
    Key=file_name,
    Metadata={
        'x-cos-meta-key1': 'value1',
        'x-cos-meta-key2': 'value2'
    }
)
print(response['ETag'])

# 创建目录
# 对象存储中，目录是特殊的路径以‘/’结尾的 object。调用 Put Object 接口即可
try:
    dir_to_create = 'path/to/create/dir/'
    response = client.put_object(
        Bucket=bucket,
        Key=dir_to_create,
        Body=b'',
    )
    print(response)
except CosServiceError as e:
    print(e.get_status_code())
